package com.farm.wcp.util;

import com.farm.wcp.api.util.HttpUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class FeiShuApi {

    private static final String BASE_URL = "https://open.feishu.cn/open-apis";
    //    public static final String APP_ID = "cli_9fd2f91db175500d"; // 千励
//    private static final String APP_SEC = "JEMck4QJJayC5L33Gw4pvbt3TzvGFKRe";
    public static final String APP_ID = "cli_9fd6df699130d00c"; // 2020通信大赛
    private static final String APP_SEC = "pKLeXz3GualD4AB1tgDkpbf7ERXk5VML";
    private static String sAppToken = null;
    private static String sTenantToken = null;
    private static FeiShuApi sInstance = null;

    public static FeiShuApi getInstance() {
        if (sInstance == null) {
            sInstance = new FeiShuApi();
        }
        JSONObject appToken = fetchAppToken();
        sAppToken = appToken.getString("app_access_token");
        sTenantToken = appToken.getString("tenant_access_token");
        return sInstance;
    }

    private static JSONObject fetchAppToken() {
        String url = BASE_URL + "/auth/v3/app_access_token/internal/";
        Map<String, String> data = new HashMap<>();
        data.put("app_id", APP_ID);
        data.put("app_secret", APP_SEC);
        return HttpUtils.httpPost(url, data);
    }

    public static JSONObject fetchUserContact(String openId) {
        String url = BASE_URL + "/contact/v1/user/batch_get?open_ids=" + openId;
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + sTenantToken);
        JSONObject res = HttpUtils.httpGet(url, headers);
        return res.getJSONObject("data").getJSONArray("user_infos").getJSONObject(0);
    }

    public static JSONObject fetchDepartInfo(String departId) {
        String url = BASE_URL + "/contact/v1/department/info/get?department_id=" + departId;
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + sTenantToken);
        JSONObject res = HttpUtils.httpGet(url, headers);
        return res.getJSONObject("data").getJSONObject("department_info");
    }

    public JSONArray fetchDepartInfos() {
        String url = BASE_URL + "/contact/v1/department/simple/list?fetch_child=true&department_id=0&page_size=100";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + sTenantToken);
        JSONObject res = HttpUtils.httpGet(url, headers);
        return res.getJSONObject("data").getJSONArray("department_infos");
    }

    public JSONObject fetchUserAccount(String code) {
        String url = BASE_URL + "/authen/v1/access_token";
        Map<String, String> data = new HashMap<>();
        data.put("app_access_token", sAppToken);
        data.put("grant_type", "authorization_code");
        data.put("code", code);
        String json = JSONObject.valueToString(data);
        JSONObject res = HttpUtils.httpPostJson(url, json);
        if (res != null && res.optInt("code", -1) == 0) {
            JSONObject user = res.getJSONObject("data");
            JSONObject userContact = fetchUserContact(user.optString("open_id"));
            if (userContact.has("departments")) {
                String departId = userContact.getJSONArray("departments").getString(0);
                JSONObject departInfo = fetchDepartInfo(departId);
                user.put("depart_id", departInfo.getString("id"));
            }
            return user;
        } else {
            throw new Error("FetchUserAccount failed: " + res.optString("msg"));
        }
    }
}
